<?php
include($GLOBALS['ROO'].'Modules/Compliance/class.compliance.php');

class Operative {

    public function Operative_MakePayOrder($Entidade, $Channel, $SelectedOrders) {
        global $sysTime, $SESSID;


        if ($SelectedOrders == '') {
            $Msg_ERROR = "Necessário seleccionar remessas.";
        }
        if (!isset($Msg_ERROR)) {
            if ($Channel == 1) {
                if ($Entidade == '') {
                    //============== Reg transact_makepayorder
                    $GET = $GLOBALS['MYT']->db_array("SELECT Op_Orden,FraCorresponsal,FraMonCobro,FraMonDPago,COUNT(FraID) AS CFra
                            FROM facturas
                            LEFT OUTER JOIN ordenespago ON Op_Corr = FraCorresponsal AND FraMonCobro = Op_MonCobro AND FraMonDPago = Op_MonDPago AND Op_Enviada = 0
                            WHERE FraID IN ({$SelectedOrders}) AND FraStatus = 2 AND FraModo = 1 GROUP BY FraCorresponsal,FraMonCobro,FraMonDPago");
                    $CGET = $GET[0];
                    for ($c = 1; $c <= $CGET; $c++) {
                        if (!isset($GET[$c]['Op_Orden'])) {
                            $GLOBALS['MYT']->db_query("INSERT INTO ordenespago (Op_Corr,Op_Fecha,Op_User,Op_MonCobro,Op_MonDPago) VALUES ({$GET[$c]['FraCorresponsal']},'$sysTime',$_SESSION[$SESSID],{$GET[$c]['FraMonCobro']},{$GET[$c]['FraMonDPago']})");
                            $QPO = $GLOBALS['MYT']->db_array("SELECT Op_Orden FROM ordenespago WHERE Op_Enviada = 0 AND Op_Corr = {$GET[$c]['FraCorresponsal']} AND Op_MonCobro = {$GET[$c]['FraMonCobro']} AND Op_MonDPago = {$GET[$c]['FraMonDPago']}");
                            $GET[$c]['Op_Orden'] = $QPO[1]['Op_Orden'];
                            unset($QPO);
                        } elseif (isset($GET[$c]['Op_Orden'])) {
                            $GLOBALS['MYT']->db_query("UPDATE ordenespago SET Op_Fecha = '$sysTime' WHERE Op_Orden = {$GET[$c]['Op_Orden']}");
                        }
                        if (isset($GET[$c]['Op_Orden'])) {
                            ####
                            ## Passar transact_makepayorder para stored procedure
                            ####
                            #### Aplica Numero e data de Factura (Pagamento Autorizado) #### Channel 1
                            $QurCPO = $GLOBALS['MYT']->db_array("SELECT CntValor FROM contadores WHERE CntCampo = 924;");
                            $GLOBALS['MYT']->db_query("UPDATE facturas SET
                FraNumero = {$QurCPO[1]['CntValor']}+FIND_IN_SET(FraID,'{$SelectedOrders}'),
                FraFecha = '{$sysTime}',
                FraStatus = 3,
                FraOrdenPago = ({$GET[$c]['Op_Orden']})
                WHERE FraID IN ({$SelectedOrders})
                AND FraStatus = 2
                AND FraCorresponsal = {$GET[$c]['FraCorresponsal']}
                AND FraMonCobro = {$GET[$c]['FraMonCobro']}
                AND FraMonDPago = {$GET[$c]['FraMonDPago']}
                AND FraModo = 1");
                            $GLOBALS['MYT']->db_query("UPDATE contadores SET CntValor = (SELECT MAX(FraNumero) FROM Facturas) WHERE CntCampo = 924;");
                            $GLOBALS['MYT']->db_query("UPDATE contadores SET CntValor = CntValor-{$GET[$c]['CFra']} WHERE CntCampo = 930;");
                            $GLOBALS['MYT']->db_query("UPDATE contadores SET CntValor = CntValor+1 WHERE CntCampo = 931;");
                            ####
                        } else {
                            $Msg_ERROR = "Nao foi possivel gerar esta ordem.";
                        }
                    }
                } elseif ($Entidade != '') {
                    //============== Reg PAY ORDER
                    $GET = $GLOBALS['MYT']->db_array("SELECT Op_Orden,{$Entidade} AS FraCorresponsal,FraMonCobro,FraMonDPago,COUNT(IF(FraStatus=2,FraID,null)) AS CFra
                            FROM facturas
                            LEFT OUTER JOIN ordenespago ON Op_Corr = {$Entidade} AND FraMonCobro = Op_MonCobro AND FraMonDPago = Op_MonDPago AND Op_Enviada = 0
                            WHERE FraID IN ({$SelectedOrders}) AND FraStatus IN (2,3) AND FraModo = 1 GROUP BY FraMonCobro,FraMonDPago");
                    $CGET = $GET[0];
                    for ($c = 1; $c <= $CGET; $c++) {
                        if (!isset($GET[$c]['Op_Orden'])) {
                            $GLOBALS['MYT']->db_query("INSERT INTO ordenespago (Op_Corr,Op_Fecha,Op_User,Op_MonCobro,Op_MonDPago) VALUES ({$GET[$c]['FraCorresponsal']},'$sysTime',$_SESSION[$SESSID],{$GET[$c]['FraMonCobro']},{$GET[$c]['FraMonDPago']})");
                            $QPO = $GLOBALS['MYT']->db_array("SELECT Op_Orden FROM ordenespago WHERE Op_Enviada = 0 AND Op_Corr = {$GET[$c]['FraCorresponsal']} AND Op_MonCobro = {$GET[$c]['FraMonCobro']} AND Op_MonDPago = {$GET[$c]['FraMonDPago']}");
                            $GET[$c]['Op_Orden'] = $QPO[1]['Op_Orden'];
                            unset($QPO);
                        } elseif (isset($GET[$c]['Op_Orden'])) {
                            $GLOBALS['MYT']->db_query("UPDATE ordenespago SET Op_Fecha = '$sysTime' WHERE Op_Orden = {$GET[$c]['Op_Orden']}");
                        }
                        if (isset($GET[$c]['Op_Orden'])) {
                            //============== Chg ORDERS
                            $QurCPO = $GLOBALS['MYT']->db_array("SELECT CntValor FROM contadores WHERE CntCampo = 924;");
                            $GLOBALS['MYT']->db_query("UPDATE Facturas SET
											FraNumero = IF(FraStatus = 2, {$QurCPO[1]['CntValor']}+FIND_IN_SET(FraID,'{$SelectedOrders}'), FraNumero),
											FraFecha = IF(FraStatus = 2, '{$sysTime}', FraFecha),
											FraStatus = 3,
											FraCorresponsal = {$Entidade},
											FraOrdenPago = {$GET[1]['Op_Orden']}
											WHERE FraID IN ({$SelectedOrders})
											AND FraStatus IN (2,3)");

                            $GLOBALS['MYT']->db_query("UPDATE contadores SET CntValor = (SELECT MAX(FraNumero) FROM Facturas) WHERE CntCampo = 924;");
                            $GLOBALS['MYT']->db_query("UPDATE contadores SET CntValor = CntValor-{$GET[$c]['CFra']} WHERE CntCampo = 930;");
                            $GLOBALS['MYT']->db_query("UPDATE contadores SET CntValor = CntValor+1 WHERE CntCampo = 931;");
                        } else {
                            $Msg_ERROR = "Nao foi possivel gerar esta ordem.";
                        }
                    }
                } else {
                    $Msg_ERROR = "Indique um correspondente.";
                }
            }
            if ($Channel == 2) {
                ## Correccao sem submissao de dominio de destino
                if ($Entidade < 1) {
                    $Entidade = 0;
                }
                $GLOBALS['MYT']->db_query("UPDATE facturas SET
            FraOrigen0=IF({$Entidade} > 0,{$Entidade},FraOrigen0),
            FraOrigen1=FraOrigen0
            WHERE FraID IN ({$SelectedOrders})
            AND FraStatus IN (3,16)
            AND FraModo = 2
            AND FraModoPago = 2");

                #### Aplica Numero e data de Guia de Remessa (Pagamento Autorizado) #### Channel 2
                $QurCPO = $GLOBALS['MYT']->db_array("SELECT CntValor FROM contadores WHERE CntCampo = 923;");
                if (!isset($QurCPO[1])) {
                    die();
                }
                $GLOBALS['MYT']->db_query("UPDATE facturas SET
            FraOrigen0=IF(FraModoPago=2,IF({$Entidade}>0,{$Entidade},FraAgenciaPago),FraOrigen0),
            FraOrigen1=FraOrigen0,
            FraAlbaran = {$QurCPO[1]['CntValor']}+FIND_IN_SET(FraID,'{$SelectedOrders}'),
            FraFechaAlb = '{$sysTime}',
            FraStatus = 16
            WHERE FraID IN ({$SelectedOrders})
            AND FraStatus = 3
            AND FraAlbaran = 0
            AND FraModo = 2
            AND (FraModoPago = 2 AND (FraAgenciaPago > 0 OR FraAgenciaPago = 0 AND {$Entidade} > 0) OR FraModoPago = 1)
            ORDER BY FraID");
                $GLOBALS['MYT']->db_query("UPDATE contadores SET CntValor = (SELECT MAX(FraAlbaran) FROM facturas) WHERE CntCampo = 923;");
                ####
                ### linha referenciaag 			FraReferenciaAg=IF(FraReferenciaAg = 0,(SELECT cor_Valor+1 FROM contadores_origens WHERE cor_Origen = {$Entidade})+1+FIND_IN_SET(FraID,'{$SelectedOrders}'),FraReferenciaAg),
                # Aplica referencia de Agencia, Alteracao convertida em segundo query
                # Atribuicao de referencia passada para passo de pagamento
                # $QurCPO = $GLOBALS['MYT']->db_array("SELECT cor_Valor+1 AS CounterOri, FraOrigen0
                #  FROM facturas
                #  INNER JOIN contadores_origens ON cor_Origen = FraOrigen0
                #  WHERE FraAlbaran > 0
                #  AND FraOrigen1 > 0
                #  AND Modo = 2
                #  GROUP by ");
                #  INSERT INTO contadores_origens (cor_Origen,cor_Valor)
                #  VALUES (va22,CounterOri) ON DUPLICATED KEY cor_Origen UPDATE cor_Valor = CounterOri

                $GET = $GLOBALS['MYT']->db_array("SELECT COUNT(FraID) AS CFra FROM facturas
                        WHERE FraID IN ({$SelectedOrders})
                        AND FraStatus = 16
                        AND FraAlbaran > 0
                        AND FraModo = 2
                        AND FraFechaAlb = '{$sysTime}'");
                if (isset($GET[1]) > 0) {
                    $GLOBALS['MYT']->db_query("UPDATE contadores SET CntValor = CntValor-{$GET[1]['CFra']} WHERE CntCampo = 930;");
                }
            }
        }
    }

    public function Operative_ValidatePayOrder($PayOrder) {

        global $__sys,$sysTime, $SESSID;

        $GetTransNumber = 1;
## Get Correspondent Data
        $GetCorrInfo = $GLOBALS['MYT']->db_array("SELECT
    tcmtID
    FROM trn_corrmethods 
    WHERE  tcmtCorrespondent = {$PayOrder['Op_Corr']} AND tcmtPID IN (161,162) AND tcmtChannel = " . $PayOrder['Op_Modo']);

        ## Verifica se esta defenido um metodo de pagamento para o correspondente, caso nao, anula validamento de pagamento

        if (metodoDePagamentoDefinido($GetCorrInfo[1])) {
            ## LOOP Make Payment by Correspondent and Mode (Multimodo desactivado, so permide pagar um canal de cada vez)
            if ($PayOrder['Op_Modo'] == 1) {
                $GetLastTrans = $GLOBALS['MYT']->db_array("
                SELECT
                MAX(Trs_CorrTrans) AS TrsCorrTrans
                FROM transmitions
                WHERE Trs_Modo = 1
                AND Trs_Corr = " . $PayOrder['Op_Corr']);
                if (isset($GetLastTrans[1])) {
                    $GetTransNumber += $GetLastTrans[1]['TrsCorrTrans'];
                }
                $GLOBALS['MYT']->db_query("INSERT
            INTO transmitions (Trs_Time, Trs_User, Trs_Corr, Trs_CorrTrans, TrsDate)
            VALUES ('{$sysTime}',{$_SESSION[$SESSID]},{$PayOrder['Op_Corr']},{$GetTransNumber},'{$sysTime}')");
                $GetTrn = $GLOBALS['MYT']->db_array("SELECT
            Trs_ID,
            Trs_CorrTrans
            FROM transmitions
            WHERE Trs_Corr = {$PayOrder['Op_Corr']}
            AND Trs_User = {$_SESSION[$SESSID]}
            AND Trs_Time = '{$sysTime}'
            ORDER BY Trs_ID DESC LIMIT 0,1");
                $TrnID = $GetTrn[1]['Trs_ID'];
                $TrnCorrID = $GetTrn[1]['Trs_CorrTrans'];
                $TransmissionResultCode = 0;
                //============== Chg ORDERS
                $GLOBALS['MYT']->db_query("UPDATE ordenespago SET
            Op_Transmision = {$TrnID},
            Op_User = {$_SESSION[$SESSID]},
            Op_Enviada = 1
            WHERE Op_Orden IN ({$PayOrder['SelectedPayOrders']})
            AND Op_Transmision IS NULL
            AND Op_Enviada = 0
            AND Op_Corr = {$PayOrder['Op_Corr']}
            AND Op_Modo = {$PayOrder['Op_Modo']}");
            }
            ### Correcao de canal
            ### Aplicar Numeracao de correspondente e fechar valores de financeiro, decidir se fica neste processo ou no processo inicial de importacao

            if ($PayOrder['Op_MonCobro'] > 0 && $PayOrder['Op_MonCobro'] == $PayOrder['Op_MonDPago']) {
                $GLOBALS['MYT']->db_query("INSERT INTO ordenesfinanceiro (Of_Orden, Of_Rate1, Of_Rate2, Of_Rate3, Mon1, Mon2, Iso1, Iso2, Rate2Time, Rate3Time, Rate2User, Rate3User)
                    VALUES ({$PayOrder['SelectedPayOrders']},'0',1,1,0,0,'','','{$sysTime}','{$sysTime}',{$_SESSION[$SESSID]},{$_SESSION[$SESSID]})");
            }
            if ($PayOrder['Op_Modo'] == 1) {
                $QurCPO = $GLOBALS['MYT']->db_query("UPDATE contadores SET CntValor = CntValor+1 WHERE CntCampo = 925");

                $CNC = $GLOBALS['MYT']->db_array("SELECT CncValor FROM contadores_corresponsal WHERE CncCorr = {$PayOrder['Op_Corr']}");

                if (!isset($CNC[1])) {
                    $CNC = $GLOBALS['MYT']->db_array("SELECT
                MAX(FraReferenciaCo) AS CncValor
                FROM facturas
                WHERE FraCorresponsal = {$PayOrder['Op_Corr']}");
                    $GLOBALS['MYT']->db_query("INSERT INTO contadores_corresponsal (CncValor,CncCorr)
                VALUES ({$CNC[1]['CncValor']},{$PayOrder['Op_Corr']})");
                }
                $CNC = $CNC[1]['CncValor'];
            }

            switch ($PayOrder['Op_Modo']) {
                case 1:
                    $GetPayOrderInvoices = $GLOBALS['MYT']->db_array("SELECT FraID
				FROM facturas WHERE FraOrdenPago IN ({$PayOrder['SelectedPayOrders']})
            	AND FraOrdenTrans IS NULL
            	AND FraStatus = 3
            	AND FraCorresponsal = {$PayOrder['Op_Corr']}
            	AND FraModo = " . $PayOrder['Op_Modo']);
                    $CGetPayOrderInvoices = $GetPayOrderInvoices[0];
                    $GLOBALS['MYT']->db_query("UPDATE contadores_corresponsal SET CncValor = " . ($CNC + $CGetPayOrderInvoices) . " WHERE CncCorr = {$PayOrder['Op_Corr']}");
                    break;
                case 2:
                    $GetPayOrderInvoices = $GLOBALS['MYT']->db_array("SELECT FraID FROM facturas
            	INNER JOIN facturas_income ON FraID = FraIncID
            	WHERE FraIncOrdenPago IN ({$PayOrder['SelectedPayOrders']})
            	AND FraIncCorresponsal = {$PayOrder['Op_Corr']}
            	AND FraModo = {$PayOrder['Op_Modo']}");
                    $CGetPayOrderInvoices = $GetPayOrderInvoices[0];
                    break;
            }

            #### Start Transmission
            $PayOrderInvoices = $GetPayOrderInvoices[1]['FraID'];
            for ($d = 2; $d <= $CGetPayOrderInvoices; $d++) {
                $PayOrderInvoices .= $GetPayOrderInvoices[$d]['FraID'] . ',';
            }
            switch ($PayOrder['Op_Modo']) {
                case 1:
                    $_GET['pr'] = 'outgoingtransaction';
                    $doTransaction = new Transact();
                    $doTransaction->transaction($PayOrder['Op_Corr'], 162, $TrnID, $PayOrder['SelectedPayOrders'],$CNC);
                    unset($doTransaction);
                    $TransmissionResultCode = 2;
                    $QurPO = $GLOBALS['MYT']->db_query("UPDATE facturas SET
                FraOrdenTrans = {$TrnID},
                FraReferenciaCo = {$CNC}+1+FIND_IN_SET(FraID,'{$PayOrderInvoices}'),
				FraStatus = 7
				WHERE FraOrdenPago IN ({$PayOrder['SelectedPayOrders']})
				AND FraOrdenTrans IS NULL
				AND FraStatus = 3
				AND FraCorresponsal = {$PayOrder['Op_Corr']}
				AND FraModo = " . $PayOrder['Op_Modo']);
                    $GLOBALS['MYT']->db_query("UPDATE ordenespago SET
				Op_Enviada = 1,
				Op_Transmision = {$TrnID},
				Op_User = {$_SESSION[$SESSID]}
				WHERE Op_Orden IN ({$PayOrder['SelectedPayOrders']})
				AND Op_Enviada = 0");

                    break;
                case 2:
                    $_GET['pr'] = 'incomingtransaction';
                    $PID = 161;
                    $TransmissionResultCode = 2;
                    ## Confirmacao para Canal de recepcao
                    $GLOBALS['MYT']->db_query("UPDATE facturas
                INNER JOIN facturas_income ON FraID = FraIncID
				SET
				FraStatus = 3
				WHERE FraIncOrdenPago IN ({$PayOrder['SelectedPayOrders']})
				AND FraStatus = 2
				AND FraIncCorresponsal = {$PayOrder['Op_Corr']}
				AND FraModo = " . $PayOrder['Op_Modo']);
                    $GLOBALS['MYT']->db_query("UPDATE ordenespago SET
				Op_Enviada = 1
				WHERE Op_Orden IN ({$PayOrder['SelectedPayOrders']})
				AND Op_Enviada = 0
				AND Op_Corr = {$PayOrder['Op_Corr']}
				AND Op_Modo = {$PayOrder['Op_Modo']}");
                    ## Auto PayOrder para canal de entrada
                    $GetInvoicesToPay = $GLOBALS['MYT']->db_array("SELECT GROUP_CONCAT(FraID SEPARATOR ',') AS InvoiceToPayList FROM facturas
                                INNER JOIN facturas_income ON FraIncID = FraID
                                WHERE FraStatus = 3
				AND FraIncOrdenPago IN ({$PayOrder['SelectedPayOrders']})
				AND FraIncCorresponsal = {$PayOrder['Op_Corr']}
				AND FraModo = " . $PayOrder['Op_Modo']);
                    if ($GetInvoicesToPay[1]['InvoiceToPayList'] != '') {
                        #AutoAprovacao de Pagamento de Lote
                        $AMLCheck = new Compliance();
                        $this->Operative_MakePayOrder('', $PayOrder['Op_Modo'], $GetInvoicesToPay[1]['InvoiceToPayList']);
                        $IncomingAML = $AMLCheck->AMLBulkBlock(2,'ReceiverName', $__sys['Country'], $GetInvoicesToPay[1]['InvoiceToPayList'], $__sys['Currency']);
                        
                    }
                    ## End Auto PayOrder
                    break;
            }
            $GLOBALS['MYT']->db_query("UPDATE contadores SET CntValor = CntValor-1 WHERE CntCampo = 931;");
        }
    }

}

?>
